﻿using System;
using System.Collections.Generic;
using System.Text;
using Catalina.Dal;
using System.Windows.Forms;
using System.ComponentModel;
using Catalina.Common;
using System.Collections.ObjectModel;

namespace Catalina.MVP
{
	public class CatalinaPresenter
	{
		private String corpConnectionString;
		private String storeConnectionString;
		private CatalinaPrintView view;
		private CatalinaModel model;
		private String xmlPath;
		private String catalinaLabelPath;

		public CatalinaPresenter(
			String corpConnectionString, 
			String storeConnectionString,
			String xmlPath,
			String catalinaLabelPath,
			CatalinaModel model,
			CatalinaPrintView view)
		{
			this.xmlPath = xmlPath;
			this.catalinaLabelPath = catalinaLabelPath;
			this.view = view;
			this.view.TimeToPrint += new CatalinaPrintView.CatalinaPrintEventHandler(View_TimeToPrint);
			this.storeConnectionString = storeConnectionString;
			this.corpConnectionString = corpConnectionString;
			this.model = model;
			this.model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Model_PropertyChanged);
		}

		void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "HeadersTable":
					view.UpdateHeaders(model.Headers);
					break;
				default:
					break;
			}
		}

		public void Initialize()
		{
			CatalinaService.BulkInsert(corpConnectionString, storeConnectionString);
			Collection<CatalinaHeader> headers = CatalinaService.GetHeaders(storeConnectionString);
			BindingList<CatalinaHeader> list = new BindingList<CatalinaHeader>();
			foreach (CatalinaHeader header in headers)
			{
				list.Add(header);
			}
			model.Headers = list;
		}
		
		void View_TimeToPrint(DataGridViewSelectedRowCollection rows)
		{
			if (rows.Count > 0)
			{
				List<CatalinaLabel> labels = new List<CatalinaLabel>();

				foreach (DataGridViewRow row in rows)
				{
					string startDate = row.Cells["startdate"].Value.ToString();
					Collection<CatalinaLabel> newLabels = CatalinaService.GetLabels(storeConnectionString, startDate);
					foreach (CatalinaLabel label in newLabels)
					{
						labels.Add(label);
					}
				}

				labels.Sort();

				CatalinaService.WriteXml(xmlPath, catalinaLabelPath, labels);
			}
		}

	}
}
